<?php
use sef\controller;
use sef\model;

class base_controller extends controller {
    protected $popup;

    protected function init() {
        $auth_id = session(config('user_auth_key'));
        if (!isset($auth_id)) {
            //跳转到认证网关
            redirect(url(config('user_auth_gateway')));
        }
        $this -> _assign_menu();
    }

    /**列表页面 **/
    function index() {
        $this -> _index();
    }

    function add() {
        $this -> display();
    }

    /**查看页面 **/
    function read($id) {
        $this -> _edit($id);
    }

    /**编辑页面 **/
    function edit($id) {
        $this -> _edit($id);
    }

    /** 保存操作  **/
    function save() {
        $this -> _save();
    }

    /**列表页面 **/
    protected function _index($name = APP_NAME) {
        $model = new model($name);

        $map = $this -> _search();
        if (method_exists($this, '_search_filter')) {
            $this -> _search_filter($map);
        }
        if (!empty($model)) {
            $this -> _list($model, $map);
        }
        $this -> display();
    }

    /**编辑页面 **/
    protected function _edit($id, $name = APP_NAME) {
        $model = new model($name);
        $where[] = array('id', 'eq', $id);
        $vo = $model -> where($where) -> find($id);

        if (IS_AJAX) {
            if ($vo !== false) {// 读取成功
                $return['data'] = $vo;
                $return['status'] = 1;
                $return['info'] = "读取成功";
                exit(json_encode($return));
            } else {
                $return['status'] = 0;
                $return['info'] = "读取错误";
                exit(json_encode($return));
            }
        }
        $this -> assign('vo', $vo);
        $this -> display();
        return $vo;
    }

    protected function _save($name = APP_NAME) {
        $opmode = request('opmode');
        switch($opmode) {
            case "add" :
                $this -> _insert($name);
                break;

            case "edit" :
                $this -> _update($name);
                break;

            case "del" :
                $this -> _del($name);
                break;
            default :
                $this -> error("非法操作");
        }
    }

    /** 插入新新数据  **/
    protected function _insert($name = APP_NAME) {
        $model = model($name);
        if (false === $model -> create()) {
            $this -> error($model -> get_error());
        }
        $list = $model -> add();
        if ($list !== false) {
            $this -> success('新增成功!');
        } else {
            $this -> error('新增失败!');
        }
    }

    /* 更新数据  */
    protected function _update($name = APP_NAME) {
        $model = model($name);
        if (false === $model -> create()) {
            $this -> error($model -> get_error());
        }
        $list = $model -> save();
        if (false !== $list) {
            $this -> success('编辑成功!', get_return_url());
        } else {
            $this -> error('编辑失败!');
        }
    }

    /** 删除标记  **/
    protected function _del($id, $name = APP_NAME, $return_flag = false) {
        $model = new model($name);
        if (!empty($model)) {
            if (isset($id)) {
                if (is_array($id)) {
                    $where[] = array('id', 'in', array_filter($id));
                } else {
                    $where[] = array('id', 'in', array_filter(explode(',', $id)));
                }
                $result = $model -> where($where) -> set_field("is_del", 1);
                if ($return_flag) {
                    return $result;
                }
                if ($result !== false) {
                    $this -> assign('jump_url', get_return_url());
                    $this -> success("成功删除{$result}条!");
                } else {
                    $this -> error('删除失败!');
                }
            } else {
                $this -> error('删除失败!');
            }
        } else {
            $this -> error('删除失败!');
        }
    }

    /** 永久删除数据  **/
    protected function _destory($id, $name = APP_NAME, $return_flag = false) {
        $model = new model($name);
        if (!empty($model)) {
            if (is_array($id)) {
                $where[] = array('id', 'in', array_filter($id));
            } else {
                $where[] = array('id', 'in', array_filter(explode(',', $id)));
            }

            if ($this -> app_type == "personal") {
                $where[] = array('user_id', 'eq', get_user_id());
            }

            $result = $model -> where($where) -> delete();
            if ($return_flag) {
                return $result;
            }
            if ($result !== false) {
                $this -> success("彻底删除{$result}条!");
            } else {
                $this -> error('删除失败!');
            }
        } else {
            $this -> error('删除失败!');
        }
    }

    protected function _chunk_upload() {

        // Make sure file is not cached (as it happens for example on iOS devices)
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        @set_time_limit(5 * 60);

        $target_dir = sys_get_temp_dir();
        $cleanup_target_dir = true;
        $max_file_age = 5 * 3600;
        if (!file_exists($target_dir)) {
            @mkdir($target_dir);
        }
        if (isset($_REQUEST['name'])) {
            $file_name = request('name');
        } elseif (!empty($_FILES)) {
            $file_name = $_FILES["file"]["name"];
        } else {
            $file_name = uniqid("file_");
        }

        $file_path = $target_dir . DS . md5($file_name);
        // Chunking might be enabled
        $chunk = isset($_REQUEST['chunk']) ? intval($_REQUEST['chunk']) : 0;
        $chunks = isset($_REQUEST['chunks']) ? intval($_REQUEST['chunks']) : 0;

        // Remove old temp files
        if ($cleanup_target_dir) {
            if (!is_dir($target_dir) || !$dir = opendir($target_dir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmp_file_path = $target_dir . DS . $file;

                // If temp file is current file proceed to the next
                if ($tmp_file_path == "{$file_path}.part") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.part$/', $file) && (filemtime($tmp_file_path) < time() - $max_file_age)) {
                    @unlink($tmp_file_path);
                }
            }
            closedir($dir);
        }
        // Open temp file
        if (!$out = @fopen("{$file_path}.part", $chunks ? "ab" : "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }
        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        if (isset($_POST['is_img_upload'])) {
            $is_img_upload = true;
        } else {
            $is_img_upload = false;
        }

        if (!$chunks || $chunk == $chunks - 1) {
            rename("{$file_path}.part", $file_path);
            $file['name'] = $file_name;
            $file['type'] = $_FILES['file']['type'];
            $file['tmp_name'] = $file_path;
            $file['size'] = filesize($file_path);
            $file['is_img_upload'] = $is_img_upload;
            return $file;
        }
        die ;
    }

    protected function _upload() {
        if (config('chunk_upload')) {
            $file = $this -> _chunk_upload();
        } else {
            $file = $_FILES;
        }
        /* 调用文件上传组件上传文件 */
        $info = model('file') -> upload($file);

        /* 记录附件信息 */
        if ($info) {
            if (!empty($info['is_img_upload'])) {
                $return = $info;
                $return['url'] = $return['url'];
            }
            $return['sid'] = $info['id'];
            $return['status'] = 1;
            $return['error'] = 0;
        } else {
            $return['status'] = 0;
            $return['info'] = $file_model -> get_error();
        }
        ajax_return($return);
    }

    protected function _down($sid) {
        $file_id = decrypt($sid);
        $file_model = model('file');
        if (false === $file_model -> download($file_id)) {
            $this -> error = $file_model -> get_error();
        }
    }

    //生成查询条件
    protected function _search($model = null) {
        if (empty($model)) {
            $model = model(APP_NAME);
        }
        $fields = $model -> get_select_fields();
        $map = array();

        foreach ($_REQUEST as $key => $val) {
            $val = trim($val);
            if ($val == '') {
                continue;
            }
            if (is_search_field($key, $fields)) {
                $prefix = substr($key, 0, 3);
                $field = substr($key, 3);
                if (($prefix == 'be_') && (isset($_REQUEST['en_' . $field]))) {
                    if (strpos($field, "time") != false) {
                        $start_time = date_to_int($val);
                        $end_time = date_to_int(trim($_REQUEST['en_' . $field])) + 86400;
                        $map[] = array($field, 'egt', $start_time);
                        $map[] = array($field, 'elt', $end_time);
                    }
                    if (strpos($field, "date") != false) {
                        $start_date = trim($val);
                        $end_date = trim($_REQUEST['en_' . $field]);
                        $map[] = array($field, 'egt', $start_date);
                        $map[] = array($field, 'elt', $end_date);
                    }
                }
                if ($prefix == 'li_') {
                    $map[] = array($field, 'like', $val);
                }
                if ($prefix == "eq_") {
                    $map[] = array($field, 'eq', $val);
                }
                if ($prefix == "gt_") {
                    $map[] = array($field, 'egt', $val);
                }
                if ($prefix == "lt_") {
                    $map[] = array($field, 'elt', $val);
                }
            }
        }
        return $map;
    }

    protected function _list($model, $map, $sort = '') {
        //排序字段 默认为主键名
        if (request('_sort')) {
            $sort = request('_sort');
        } elseif (empty($sort)) {
            $sort = "id desc";
        }
        $count_model = clone $model;
        //取得满足条件的记录数
        $count = $count_model -> where($map) -> count();
        if ($count > 0) {
            //创建分页对象
            if (request('list_rows')) {
                $list_rows = request('list_rows');
            } else {
                $list_rows = get_user_config('list_rows');
            }
            import("page/page");
            $p = new \page($count, $list_rows);

            $vo_list = $model -> where($map) -> limit($p -> first_row, $list_rows) -> order($sort) -> get_list();
            //分页显示
            $page = $p -> show();
            if ($vo_list) {
                $this -> assign('list', $vo_list);
                $this -> assign('sort', $sort);
                $this -> assign("page", $page);
                return $vo_list;
            }
        }
        return FALSE;
    }

    protected function _system_folder_manage($folder_name, $has_pid = false) {
        $system_folder = new system_folder_controller();
        $system_folder -> assign('folder_name', $folder_name);
        $system_folder -> assign('has_pid', $has_pid);
        $system_folder -> index();
    }

    protected function _user_folder_manage($folder_name, $has_pid = false) {
        $system_folder = new user_folder_controller();
        $system_folder -> assign('folder_name', $folder_name);
        $system_folder -> assign('has_pid', $has_pid);
        $system_folder -> index();
    }

    protected function _system_tag_manage($tag_name, $has_pid = false) {
        $system_tag = new system_tag_controller();
        $system_tag -> assign('tag_name', $tag_name);
        $system_tag -> assign('has_pid', $has_pid);
        $system_tag -> index();
    }

    protected function _user_tag_manage($tag_name, $has_pid = false) {
        $this -> assign('tag_name', $tag_name);
        $this -> assign('has_pid', $has_pid);
        R('UserTag/index');
    }

    protected function _field_manage($row_type) {
        $controller = new udf_field_controller();
        $controller -> folder_name = 'aa';
        $controller -> index();
    }

    /**显示top menu及 left menu **/
    private function _assign_menu() {
        $popup_list = array_filter(explode(",", $this -> popup));
        if (IS_AJAX or in_array(METHOD_NAME, $popup_list)) {
            return;
        }

        $node_model = model('node');

        $top_menu_list = $node_model -> get_top_menu(get_user_id());
        if (empty($top_menu_list)) {
            $this -> assign('jumpUrl', url("public/logout"));
            $this -> error("没有权限");
        }

        $this -> assign('top_menu_list', $top_menu_list);

        //读取数据库模块列表生成菜单项
        $menu = $node_model -> access_list();

        $system_folder_model = model('system_folder');
        $system_folder_menu = $system_folder_model -> get_folder_menu();

        $user_folder_model = model('user_folder');
        $user_folder_menu = $user_folder_model -> get_folder_menu();

        $menu = array_merge($menu, $system_folder_menu, $user_folder_menu);
        $menu = sort_by($menu, 'sort');

        //设置返回URL地址
        $return_url = get('return_url');
        if (!empty($return_url)) {            
            cookie('return_url', url($return_url));

            $top_menu_id = get_top_menu_id($return_url, $menu);
            cookie('top_menu_id', $top_menu_id);            
        } else {
            $top_menu_id = cookie('top_menu_id');
        }

        if (!empty($top_menu_id)) {
            $where[] = array('id', 'eq', $top_menu_id);
            $current_top_menu_name = $node_model -> where($where) -> get_field('name');

            $this -> assign("current_top_menu_name", $current_top_menu_name);
            $this -> assign("title", get_system_config("SYSTEM_NAME") . "-" . $current_top_menu_name);

            $left_menu = list_to_tree($menu, $top_menu_id);
            $this -> assign('left_menu', $left_menu);

        } else {
            $this -> assign("title", get_system_config("SYSTEM_NAME"));
        }
    }

    private function _system_log() {
        $system_log_time = cache('system_log_time');
        if (empty($system_log_time)) {
            $flag = true;
        } else {
            $flag = (time() - cache('system_log_time')) > 24 * 3600;
        }
        if ($flag) {
            $time = time();
            cache('system_log_time', $time);
            $data['time'] = $time;
            $data['type'] = 1;

            $file_model = model('file');
            $data['data'] = $file_model -> count();

            $file_model -> add($data);

            $data['type'] = 2;
            $data['data'] = $file_model -> sum('size') / 1024 / 1024;

            model("system_log") -> add($data);
        }
    }

}
?>